<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getAllPosApi, savePosApi, isRelatedApi, deletePosApi, getPosByIdApi, updatePosApi } from '../../api/hr'

//页面加载完成
onMounted(() => {
  onSubmit()
})

// 查询条件表单
const formInline = ref({ title: '', positionType: '', status: '', })
const onSubmit = async() => {
  console.log(formInline.value)
  //  去除字符串首尾空格
  if(!formInline.value.title){
    formInline.value.title = formInline.value.title.trim()
  }
  const result = await getAllPosApi(formInline.value.title, formInline.value.positionType,
   formInline.value.status, currentPage.value, pageSize.value)
  if(result.code){
    posListTable.value = result.data.rows
    total.value = result.data.total
  }else{
    ElMessage.error(result.msg)
  }
}
//清空查询条件
const clear = () => {
  formInline.value = { title: '', positionType: '', status: '', }
  currentPage.value = 1
  pageSize.value = 8
  onSubmit()
}
// 职位表格数据
const posListTable = ref([
  {
    id: 1,
    title: 'Java开发',
    salaryRange: '10k-20k',
    experienceRequired: '1-3年',
    educationRequired: '本科',
    positionType: '全职',
    status: 2,
    publishDate: '2021-01-01',
    updateTime: '2021-01-01 T 10:00:00',
  }
])
//批量删除
const selectedIds = ref([])
const handleSelectionChange = (selection) => {
  if(selection && selection.length > 0){
    selectedIds.value = selection.map( item => item.id)
  }else{
    selectedIds.value = []
  }
}
//批量删除
const deletePos = async() => {
  if(selectedIds.value.length === 0){
    ElMessage.warning('请选择要删除的职位')
    return
  }
  ElMessageBox.confirm(
    `确定要删除选中的职位吗？`, '提示',
    { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning', }
  ).then(async () => {
      const result = await deletePosApi(selectedIds.value)
      if(result.code){
        ElMessage.success('删除职位成功！')
        //设置当前页码和每页条数
        currentPage.value = 1
        pageSize.value = 8
        onSubmit()
      }else{
        ElMessage.error(result.msg)
      }
    })
    .catch(() => {})
}
//删除职位
const dropPos = (row) => {
  ElMessageBox.confirm(
    `确定要删除《${row.title}》职位吗？`, '提示',
    { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning', }
  ).then(async () => {
      const result = await deletePosApi(row.id)
      if(result.code){
        ElMessage.success('删除职位成功！')
        //设置当前页码和每页条数
        currentPage.value = 1
        pageSize.value = 8
        onSubmit()
      }else{
        ElMessage.error(result.msg)
      }
    })
    .catch(() => {})
}
//分页
const total = ref(20)
const currentPage = ref(1)
const pageSize = ref(8)
const background = ref(true)
//每页大小改变时触发
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  onSubmit()
}
//当前页码改变时触发
const handleCurrentChange = (val) => {
  currentPage.value = val
  onSubmit()
}
//添加职位dialog
const dialogVisible = ref(false)
const dialogTitle = ref('添加职位')
const positionForm = ref({
  title: '',
  description: '',
  requirements: '',
  salaryRange: '',
  workLocation: '',
  experienceRequired: '',
  educationRequired: '',
  positionType: '',
})
//表单引用
const posRuleRef = ref()
//表单校验规则
const posFormRules = ref({
  title: [
    { required: true, message: '请输入职位名称', trigger: 'blur' },
    { min: 2, message: '长度不小于2个字符', trigger: 'blur' },
    { max: 50, message: '长度不超过50个字符', trigger: 'blur' }
  ],
  positionType: [
    { required: true, message: '请选择职位类型', trigger: 'change' }
  ],
  workLocation: [
    { max: 255, message: '长度不超过255个字符', trigger: 'blur' }
  ],
  experienceRequired: [
    { max: 50, message: '长度不超过50个字符', trigger: 'blur' },
    { required: true, message: '请输入经验要求', trigger: 'change' }
  ],
  educationRequired: [
    { max: 50, message: '长度不超过50个字符', trigger: 'blur' },
    { required: true, message: '请选择学历要求', trigger: 'change' }
  ],
  salaryRange: [
    { max: 50, message: '长度不超过50个字符', trigger: 'blur' },
    { required: true, message: '请选择薪资范围', trigger: 'change' }
  ]
})
//打开新增窗口
const addPos = async () => {
  //查询当前企业用户是否关联了企业
  const result = await isRelatedApi()
  if(!result.code){
    ElMessage.warning(result.msg)
    return
  }
  //清除表单数据
  positionForm.value = {
    title: '',
    description: '',
    requirements: '',
    salaryRange: '',
    workLocation: '',
    experienceRequired: '',
    educationRequired: '',
    positionType: '',
  }
  if (posRuleRef.value) {
    posRuleRef.value.resetFields()
  }
  dialogTitle.value = '新增职位'
  dialogVisible.value = true
}
//保存职位
const savePos = () => {
    /* 判断表单引用是否存在 */
  if(!posRuleRef.value) return
  posRuleRef.value.validate(async (valid) => {
    /* 判断表单验证是否通过 */
    if(valid){
      console.log(positionForm.value)
      //通过positionForm.value.id是否有id执行新增还是修改
      let result;
      if(positionForm.value.id){
        result = await updatePosApi(positionForm.value)
      }else{
        result = await savePosApi(positionForm.value)
      }
      if(result.code){
        ElMessage.success('保存职位成功！')
        //设置当前页码和每页条数
        currentPage.value = 1
        pageSize.value = 8
        dialogVisible.value = false
        onSubmit()
      }else{
        ElMessage.error(result.msg)
      }
    }
  })
}
//根据id查询职位
const editPos = async (row) => {
  //职位状态为1，待审核提示信息
  if(row.status === 1){
    ElMessage.warning('该职位尚未通过审核，请耐心等待！')
    return
  }
  //职位状态为3，审核不通过提示信息
  if(row.status === 3){
    ElMessage.warning('该职位审核未通过，请重新发布！')
    return
  }
  const result = await getPosByIdApi(row.id)
  if(result.code){
    positionForm.value = result.data
    if (posRuleRef.value) {
      posRuleRef.value.resetFields()
    }
    dialogTitle.value = '修改职位'
    dialogVisible.value = true
  }else{
    ElMessage.error(result.msg)
  }
}
</script>

<template> 
  <h2>职位管理</h2>
  <!-- 查询表单 -->
  <div class="container">
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item label="职位">
        <el-input v-model="formInline.title" placeholder="输入您要查询的职位名称"/>
      </el-form-item>
      <el-form-item label="类型">
        <el-select
          v-model="formInline.positionType"
          placeholder="选择职位类型"
          style="width: 190px"
        >
          <el-option label="全职" value="全职" />
          <el-option label="实习" value="实习" />
          <el-option label="兼职" value="兼职" />
        </el-select>
      </el-form-item>
      <el-form-item label="职位状态">
        <el-select
          v-model="formInline.status"
          placeholder="选择职位状态"
          style="width: 190px"
        >
          <el-option label="待审核" value="1" />
          <el-option label="已通过" value="2" />
          <el-option label="不通过" value="3" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">查询</el-button>
        <el-button type="info" @click="clear">清空</el-button>
      </el-form-item>
    </el-form>
  </div>
  <div class="container">
    <el-button type="danger" @click="deletePos">-&nbsp;批量删除</el-button>
    <el-button type="primary" @click="addPos">+&nbsp;添加职位</el-button>
  </div>
  <!-- 添加职位dialog -->
  <el-dialog v-model="dialogVisible" :title="dialogTitle" fullscreen top="40vh" width="70%" draggable >
    <el-form ref="posRuleRef" :rules="posFormRules" :model="positionForm" label-width="120px" label-position="top" >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="职位名称" prop="title">
            <el-input v-model="positionForm.title" placeholder="请输入职位名称" maxlength="50" show-word-limit />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="职位类型" prop="positionType">
            <el-select v-model="positionForm.positionType" placeholder="请选择职位类型" style="width: 100%" >
              <el-option label="全职" value="全职" />
              <el-option label="兼职" value="兼职" />
              <el-option label="实习" value="实习" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="薪资范围" prop="salaryRange">
            <el-input v-model="positionForm.salaryRange" placeholder="例如：10k-20k" maxlength="50" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="工作地点" prop="workLocation">
            <el-input v-model="positionForm.workLocation" placeholder="请输入工作地点" maxlength="255" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="经验要求" prop="experienceRequired">
            <el-input v-model="positionForm.experienceRequired" placeholder="例如：3-5年" maxlength="50" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="学历要求" prop="educationRequired">
            <el-input v-model="positionForm.educationRequired" placeholder="例如：本科及以上" maxlength="50" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="职位描述" prop="description">
        <el-input v-model="positionForm.description" type="textarea" :rows="6" placeholder="请输入职位描述" />
      </el-form-item>
      <el-form-item label="职位要求" prop="requirements">
        <el-input v-model="positionForm.requirements" type="textarea" :rows="6" placeholder="请输入职位要求" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="savePos">确认</el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 职位表格数据 -->
  <div class="container">
    <el-table :data="posListTable" border style="width: 100%; height: 460px;" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column prop="title" label="职位名称" width="120"  align="center"/>
      <el-table-column prop="salaryRange" label="薪资范围" width="120"  align="center"/>
      <el-table-column prop="experienceRequired" label="经验要求" width="120"  align="center"/>
      <el-table-column prop="educationRequired" label="学历要求" width="120"  align="center"/>
      <el-table-column label="职位类型" width="90" align="center" >
        <template #default="scope">
          <span v-if="scope.row.positionType == `全职`">全职</span>
          <span v-else-if="scope.row.positionType == `兼职`">兼职</span>
          <span v-else-if="scope.row.positionType == `实习`">实习</span>
          <span v-else>其他</span>
        </template>
      </el-table-column>
      <el-table-column label="职位状态" width="100" align="center" >
        <template #default="scope">
          <span v-if="scope.row.status == 1">待审核</span>
          <span v-else-if="scope.row.status == 2">已发布</span>
          <span v-else-if="scope.row.status == 3">审核不通过</span>
          <span v-else>其他</span>
        </template>
      </el-table-column>
      <el-table-column prop="publishDate" label="发布日期" width="160"  align="center"/>
      <el-table-column prop="updateTime" label="最后操作时间" width="200"  align="center"/>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button type="primary" plain size="small" @click="editPos(scope.row)">编辑</el-button>
          <el-button type="danger" plain size="small" @click="dropPos(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
  <!-- 分页 -->
  <div class="container">
  <el-pagination
    v-model:current-page="currentPage"
    v-model:page-size="pageSize"
    :page-sizes="[8, 16, 24]"
    :size="size"
    :background="background"
    layout="total, sizes, prev, pager, next, jumper"
    :total="total"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
  />
  </div>
</template>

<style scoped>
  h2{
    font-size: 24px;
  }
  .container {
    margin-top: 10px;
  }
  .demo-form-inline .el-input {
    --el-input-width: 220px;
  }

  .demo-form-inline .el-select {
    --el-select-width: 220px;
  }
</style>